<template>
  <el-card>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-button type="success" plain @click="addGood">添加商品</el-button>

    <el-table :data="goodsList" style="width: 100%">
      <el-table-column prop="goods_id" label="商品Id" width="100">
      </el-table-column>
      <el-table-column prop="goods_name" label="商品名" width="250">
      </el-table-column>
      <el-table-column prop="goods_price" label="商品价格" width="120">
      </el-table-column>
      <el-table-column prop="goods_number" label="商品数量" width="120">
      </el-table-column>
      <el-table-column prop="goods_weight" label="商品重量" width="120">
      </el-table-column>
    <!--   <el-table-column prop="goods_state" label="商品状态" width="120">
      </el-table-column> -->
      <el-table-column prop="add_time" label="添加时间" width="200">
      </el-table-column>
      <el-table-column prop="upd_time" label="更新时间" width="200">
      </el-table-column>
      <el-table-column prop="hot_mumber" label="热销品数量" width="120">
      </el-table-column>
      <el-table-column prop="is_promote" label="是否热销" width="120">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <!-- <span class="demonstration">完整功能</span> -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="getGoods.pagenum"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="getGoods.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog title="修改商品" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm" :rules="addFormRules" ref="editForm">
        <el-form-item label="商品名称" prop="goods_name">
          <el-input
            v-model="editForm.goods_name"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="goods_price">
          <el-input
            v-model="editForm.goods_price"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="goods_number">
          <el-input
            v-model="editForm.goods_number"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="goods_cat">
          <el-cascader
            v-model="selectededitOptions"
            :options="categoriesList"
            :props="props"
            clearable
            style="margin-bottom:20px"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="重量" prop="goods_weight">
          <el-input
            v-model="editForm.goods_weight"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="goods_introduce">
          <el-input
            v-model="editForm.goods_introduce"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="pics">
          <el-input v-model="editForm.pics" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品参数" prop="attrs">
          <el-input v-model="editForm.attrs" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editGoodSubmit('editForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog title="添加商品" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" :rules="addFormRules" ref="addForm">
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="addForm.goods_name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="goods_price">
          <el-input
            v-model="addForm.goods_price"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="goods_number">
          <el-input
            v-model="addForm.goods_number"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="goods_cat">
          <el-cascader
            v-model="selectedaddOptions"
            :options="categoriesList"
            :props="props"
            clearable
            style="margin-bottom:20px; width: 300px"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="重量" prop="goods_weight">
          <el-input
            v-model="addForm.goods_weight"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="goods_introduce">
          <el-input
            v-model="addForm.goods_introduce"
            auto-complete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="pics">
          <el-upload
            action="http://47.96.21.88:8888/api/private/v1/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品参数" prop="attrs">
          <el-input v-model="addForm.attrs" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addGoodSubmit('addForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getCategories,
  getGoods,
  addGoods,
  editGoods,
  deleteGoods
} from "../../api/index";

import dateFormat from "../../uitils/formatDate"

export default {
  name: "",
  data() {
    return {
      categoriesList: [],
      selectedaddOptions: [],
      selectededitOptions: [],
      props: {
        value: "cat_id",
        label: "cat_name"
      },

      getGoods: {
        query: "",
        pagenum: 1,
        pagesize: 5
      },
      goodsList: [],
      total: 0,
      editDialogFormVisible: false,
      editForm: {
        goods_id: "",
        goods_name: "",
        goods_price: "",
        goods_number: "",
        goods_cat: "",
        goods_weight: "",
        goods_introduce: "",
        pics: "",
        attrs: ""
      },

      addFormRules: {
        goods_name: [
          { required: true, message: "请填写商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请填写商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请填写商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请填写商品数量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ]
      },

      addDialogFormVisible: false,
      addForm: {
        goods_name: "",
        goods_price: "",
        goods_number: "",
        goods_cat: "",
        goods_weight: "",
        goods_introduce: "",
        pics: [],
        attrs: "",
        goods_state: 1
      }
    };
  },
  watch: {},
  props: {},
  components: {},
  computed: {},
  mounted() {
    this.initGoodsList();
    this.initGetCategories();
  },
  methods: {
    async initGetCategories() {
      let { data, meta } = await getCategories(this.getCategoriesList);
      if (meta.status !== 200) return this.$message.error("获取失败");

      this.categoriesList = data;
    },

    async initGoodsList() {
      let { data, meta } = await getGoods(this.getGoods);
      if (meta.status !== 200)
        return this.$message.error("初始化商品列表失败！");
      this.goodsList = data.goods.reduce((pre, cur) => {
        cur.is_promote ? (cur.is_promote = "是") : (cur.is_promote = "否");
        cur.add_time = dateFormat(new Date(cur.add_time))
        cur.upd_time = dateFormat(new Date(cur.upd_time))
        return [...pre, cur];
      }, []);
      this.total = data.total;
      console.log(this.goodsList);
    },



    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.getGoods.pagesize = val;
      this.initGoodsList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.getGoods.pagenum = val;
      this.initGoodsList();
    },

    handleEdit(row) {
      this.editDialogFormVisible = true;
      this.editForm.goods_id = row.goods_id;
      this.editForm.goods_name = row.goods_name;
      this.editForm.goods_price = row.goods_price;
      this.editForm.goods_number = row.goods_number;
      this.editForm.goods_cat = row.goods_cat;
      this.editForm.goods_weight = row.goods_weight;
      this.editForm.goods_introduce = row.goods_introduce;
      this.editForm.pics = row.pics;
      this.editForm.attrs = row.attrs;
    },

    editGoodSubmit(editform) {
      console.log(this.selectededitOptions.join(","));

      this.editForm.goods_cat = this.selectededitOptions.join(",");
      this.$refs[editform]
        .validate()
        .then(async () => {
          console.log(this.editForm);
          let { data, meta } = await editGoods(this.editForm);
          console.log(meta);
          console.log(data);
          if (meta.status != 200) return this.$message.error("修改失败");
          this.editDialogFormVisible = false;

          this.$nextTick(() => {
            this.initGoodsList();
          });
        })
        .catch(err => console.log(err));
    },

    addGood() {
      this.addDialogFormVisible = true;
      this.addForm.goods_name = "";
      this.addForm.goods_price = "";
      this.addForm.goods_number = "";
      this.addForm.goods_cat = "";
      this.addForm.goods_weight = "";
      this.addForm.goods_introduce = "";
      this.addForm.pics = "";
      this.addForm.attrs = "";
    },

    addGoodSubmit(addform) {
      this.addForm.goods_cat = this.selectedaddOptions.join(",");
      console.log(this.addForm);
      this.$refs[addform]
        .validate()
        .then(async () => {
          console.log(this.addForm);
          let { data, meta } = await addGoods(this.addForm);
          console.log(meta);
          console.log(data);
          if (meta.status != 201) return this.$message.error(meta.msg);
          this.addDialogFormVisible = false;
          this.$message.success("添加成功");
          this.$nextTick(() => {
            this.initGoodsList();
          });
        })
        .catch(err => console.log(err));
    },

    handleDelete(row) {
      this.$confirm("此操作将永久删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          console.log(row);
          let { data, meta } = await deleteGoods({
            id: row.goods_id
          });
          console.log(data);
          console.log(meta);

          if (meta.status === 200) {
            this.$message.success("删除成功");
            this.$nextTick(() => {
              this.initGoodsList();
            });
          } else {
            this.$message.error(meta.msg);
          }
        })
        .catch((err) => {
          console.log(err);
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    handlePreview(result) {
      this.previewImgSrc = result.response.data.url;
      this.previewVisible = true;
    },
    handleRemove(result) {
      // 根据 result.response.data.temp_path 从 addForm.pics 数组中，找到要删除那个对象的索引值
      const index = this.addForm.pics.findIndex(
        item => item.pic === result.response.data.tmp_path
      );
      // 根据索引删除对应的图片信息对象
      this.addForm.pics.splice(index, 1);
    },

    handleSuccess(result) {
      if (result.meta.status === 200) {
        // 把上传成功后，图片的临时路径，保存到 addForm.pics 数组中，作为对象来保存
        this.addForm.pics.push(result.data.tmp_path)

      }
    }
  },
  filters: {}
};
</script>

<style scoped lang="css"></style>
